from flask import Flask, request, jsonify
import mysql.connector
from flask_cors import CORS
import bcrypt


app = Flask(__name__)
CORS(app)


# 全局数据库连接和游标
cnx = None
cursor = None


def connect_to_mysql():
    global cnx,cursor
    try:
        cnx = mysql.connector.connect(
            host="localhost",
            port=3434,
            user="root",
            password="123456",
            database="pythonsql"
        )
        if cnx.is_connected():
            print("成功连接数据库")
            cursor = cnx.cursor()
        else:
            print("数据库连接失败")
    except mysql.connector.Error as err:
        print(f"Error: {err}")


# 注册验证
def register_user(username, password):
    global cnx,cursor
    if cnx and cursor:
        try:
            # 检查连接是否仍然有效
            if cnx.is_connected():
                # 检查用户名是否已经存在
                check_query = "SELECT * FROM users WHERE username = %s"
                data = (username,)
                cursor.execute(check_query, data)
                existing_user = cursor.fetchone()
                if existing_user:
                    return jsonify({"error": "用户名已存在，请选择其他用户名"}), 400
                
                insert_query = "INSERT INTO users (username, password) VALUES (%s, %s)"
                hashed_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())
                data = (username, hashed_password)
                cursor.execute(insert_query, data)
                cnx.commit()
                return jsonify({"message": "用户注册成功"})
            else:
                return jsonify({"error": "数据库连接已断开"}), 500
        except mysql.connector.Error as err:
            return jsonify({"error": f"注册用户时出错: {err}"}), 500
    else:
        return jsonify({"error":"数据库连接失败"}),500        


# 登录验证
def login_user(username, password):
    global cnx,cursor
    if cnx and cursor:
        try:
            select_query = "SELECT * FROM users WHERE username = %s"
            data = (username,)
            cursor.execute(select_query, data)
            user = cursor.fetchone()
            if user:
                stored_password = user[2]
                if bcrypt.checkpw(password.encode('utf-8'), stored_password.encode('utf-8')):
                    return jsonify({"message": "登录成功"})
                else:
                    return jsonify({"error": "用户名或密码错误"}), 401
            else:
                return jsonify({"error": "用户名或密码错误"}), 401
        except mysql.connector.Error as err:
            return jsonify({"error": f"登录时出错: {err}"}), 500
    else:
        return jsonify({"error":"数据库连接失败"}),500


@app.route('/register', methods=['POST'])
def register():
    data = request.get_json()
    username = data.get('username')
    password = data.get('password')
    if username and password:
        return register_user(username, password)
    else:
        return jsonify({"error": "请提供用户名和密码"}), 400


@app.route('/login', methods=['POST'])
def login():
    data = request.get_json()
    username = data.get('username')
    password = data.get('password')
    if username and password:
        return login_user(username, password)
    else:
        return jsonify({"error": "请提供用户名和密码"}), 400


if __name__ == '__main__':
    connect_to_mysql()
    app.run(debug=True)